from GenerateRandomData.GenEmail import *
from GenerateRandomData.GenInt import *
from GenerateRandomData.GenName import *

from Utils.get_gen_funcs import get_gen_funcs
import re
from Utils.sql_parser import SqlParser
from Utils.read_config import read_config

class SqlParserTest:
    
    def __init__(self, sql):
        self.sql = sql
    
    def find_params(self):
        """
        input: config.ini中未解析的sql
        output: 所有!{}中的方法名
        """
        # 正则匹配到所有的!{}
        raw_params = re.findall('!{.*?}', self.sql)
        params = []
        for param in raw_params:
            # 将!{}中的方法名提取出来
            param = param[2:-1]
            params.append(param)
        return params

    def replace_params(self):
        """
        input: 解析后的方法名列表
        output: 随机生成的数据列表
        """

        params = self.find_params()

        # 获取所有定义好的随机生成数据的方法列表
        # gen_funcs = get_gen_funcs()
        gen_funcs = ['GenEmail', 'GenInt', 'GenName']
        random_data = []
        for param in params:
            if param in gen_funcs:
                random_data.append(eval(param)().generate_data())
            elif "(" in param:
                # 提取括号中的两个数字
                nums = [int(s) for s in re.findall(r'\b\d+\b', param)]
                # 提取方法名
                param = param.split("(")[0]
                random_data.append(eval(param)().generate_data(nums[0], nums[1]))
            elif "[" in param:
                # 将字符串形式的列表转换成list
                cmd_list = self.translate_str_to_list(param)
                random_data.append(random.choice(cmd_list))

        random_data_str = self.add_double_quotes_to_list(random_data)
        return random_data_str

    def add_double_quotes_to_list(self, l):
        """
        input: list
        output: 为每个list中的元素（字符串类型），加上双引号
        """

        for index, v in enumerate(l):
            if isinstance(v, int):
                l[index] = str(v)
            elif isinstance(v, str):
                l[index] = '"' + v + '"'
        return l

    def translate_str_to_list(self, s):
        """
        input: 字符串形式的列表，如：'["篮球","足球","乒乓球","羽毛球"]'
        output: 列表，转换后为：["篮球","足球","乒乓球","羽毛球"]
        """

        l = s.split(",")
        cmd = ""
        cmd_list = []
        for i in l:
            for c in i:
                if c != "[" and c != "]" and c != " " and c != '"':
                    cmd += c
            cmd_list.append(cmd)
            cmd = ""
        return cmd_list


if __name__ == "__main__":
    sql = read_config()["sql"]["sql"]
    print("origin: ", sql)
    sql_parser = SqlParserTest(sql)
    params = sql_parser.find_params()
    print("params: ", params)
    random_data = sql_parser.replace_params(params)
    print("random_data: ", random_data)
